const path = require('path')
const fs = require('fs')
function readFileAsync(filePath, encoding) {  
    return new Promise((resolve, reject) => {  
      fs.readFile(filePath, encoding, (error, data) => {  
        if (error) {  
          reject(error);  
        } else {  
          resolve(data);  
        }  
      });  
    });  
}  
function backup(filePath) {  
    return new Promise((resolve, reject) => {  
      fs.copyFile(filePath,filePath+'.utools.bak.'+new Date().getTime(), (error, data) => {  
        if (error) {  
          reject(error);  
        } else {  
          resolve(data);  
        }  
      });  
    });  
} 

function writeFile(filePath,conetnt) {  
    return new Promise((resolve, reject) => {  
      fs.writeFile(filePath,conetnt, (error, data) => {  
        if (error) {  
          reject(error);  
        } else {  
          resolve(data);  
        }  
      });  
    });  
} 

function getBookmarksPath () {

  var chromeDataDir = '';
  if (process.platform === 'win32') {
    chromeDataDir = path.join(process.env.LOCALAPPDATA, 'Google/Chrome/User Data')
    // edgeDataDir = path.join(process.env.LOCALAPPDATA, 'Microsoft/Edge/User Data')
  } else if (process.platform === 'darwin') {
    chromeDataDir = path.join(window.utools.getPath('appData'), 'Google/Chrome')
    // edgeDataDir = path.join(window.utools.getPath('appData'), 'Microsoft Edge')
  }

  const profiles = ['Default', 'Profile 3', 'Profile 2', 'Profile 1']
  
  const profile = profiles.find(profile => fs.existsSync(path.join(chromeDataDir, profile, 'Bookmarks')))
  if (!profile) return ""
  const bookmarkPath = path.join(chromeDataDir, profile, 'Bookmarks')
  return bookmarkPath
}

  
window.services = {
    readFile: (inputPath, encoding = 'utf8') => {
        return readFileAsync(inputPath, encoding)
    },
    writeFile: (inputPath, content) => {
        return writeFile(inputPath, content)
    },
    backup: (inputPath) => {
        return backup(inputPath)
    },
    getBookmarksPath:() => {
      return getBookmarksPath()
    }
       
}